package com.dddd.blog.blogcommon.utils;


import org.apache.commons.codec.binary.Hex;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 * @author 喵星球的大橘
 */
public class PasswordUtils {

    /**
     * 对密码进行MD5加密
     * @param pwd
     * @return
     */
    public static String  pwdMd5(String pwd,String salt){

        if(StringUtils.isEmpty(pwd)){
            return "";
        }

        byte[] bytes;
        try {

            if(!StringUtils.isEmpty(salt)){
                pwd += salt;
            }

            // 获取MD5实例
            MessageDigest md5 = MessageDigest.getInstance("md5");
            bytes = pwd.getBytes(StandardCharsets.UTF_8);
            byte[] data = md5.digest(bytes);
            return Hex.encodeHexString(data);
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 密码验证
     * @param pwdStr
     * @param salt
     * @param pwdStr
     * @return
     */
    public static boolean isCorrectPassword(String pwd, String salt, String pwdStr){
        if(StringUtils.isEmpty(pwd)){
            return false;
        }

        String pwdGen = pwdMd5(pwd,salt);

        if(pwdStr.equals(pwdGen)){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {

        String password = "111111";
        String salt = "admin";

        String pwdStr = pwdMd5(password,salt);

//        System.out.println(pwdStr.equals(pwdMd5(password,"helloworld")));
        System.out.println(pwdStr);
    }
}
